package org.myhibernate.excel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Element;
import org.myhibernate.core.XMLUtil;

public class ExcelMaps 
{
	private static Map<String, ExcelMap> map=new HashMap<String, ExcelMap>();
	private static Map<String, ExcelMap> classMap=new HashMap<String, ExcelMap>();
	private static List<String> nameList=new ArrayList<String>();
	public static String xmlConnfigPath="excel.xml";
	static
	{
		load();
	}
	public static void load()
	{
		int len=nameList.size();
		for (int i = len-1; i >=0 ; i--) 
		{
			nameList.remove(i);
		}
		XMLUtil xmlUtil=new XMLUtil();
		String xml="";
		try {
			xml=xmlUtil.readFile(ExcelMaps.class.getClassLoader().getResourceAsStream(xmlConnfigPath), "utf-8");
		} catch (Exception e) {
			System.out.println("Exception for load : "+xmlConnfigPath);
			e.printStackTrace();
			return;
		}
		//System.out.println("xml="+xml);
		List<Element> list=null;
		Element element=null;
		Element root=null;
		//get language
		try {
			root=xmlUtil.getXmlRoot(xml);
			
			//list=xmlUtil.getXmlChildren(xml, "mapping");
			list=root.getChildren("excel");
			//System.out.println("mapping.size="+list.size());
			for (int i = 0; i < list.size(); i++)
			{
				Element excelElement=list.get(i);
				ExcelMap excel=new ExcelMap();
				map.put(excelElement.getAttributeValue("filename"), excel);
				classMap.put(excelElement.getAttributeValue("classname"), excel);
				if (nameList.contains(excelElement.getAttributeValue("filename"))==false) {
					nameList.add(excelElement.getAttributeValue("filename"));
				}
				Element idElement=excelElement.getChild("id");
				if (idElement != null)
				{
					excel.setIdTitle(idElement.getAttributeValue("title"));
					excel.setIdField(idElement.getAttributeValue("column"));
				}
				
				List<Element> cols=excelElement.getChildren("column");
				for (int j = 0; j < cols.size(); j++) 
				{
					element=cols.get(j);
					excel.set(element.getAttributeValue("title"), element.getAttributeValue("column"));
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	public static ExcelMap getExcelMap(String fileName)
	{
		return map.get(fileName);
	}
	public static Map<String, ExcelMap> getMap() {
		return map;
	}
	public static void main(String[] args) {
		System.out.println(getMap());
	}
	public static List<String> getNameList() {
		return nameList;
	}
	public static Map<String, ExcelMap> getClassMap() {
		return classMap;
	}
}
